package com.hjw.dynamicdatasource.service;


import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;

/**
 * @author ivan(黄俊玮)
 * FileName: DataSourceFactoryService
 * Date: 2025/10/29 16:03
 */
@Service
public class DataSourceFactoryService {

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public String refreshDataSource(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        // 关键：使用动态数据源
        sessionFactory.setDataSource(dataSource);
        // 其他配置（如mapper位置）...
        sqlSessionFactory = sessionFactory.getObject();
        return sqlSessionFactory.getConfiguration().getDatabaseId();
    }
}
